package top.lshaci.learning.netty.rpc.provider;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * NettyServer
 *
 * @author lshaci
 * @since 1.0.0
 */
public class NettyServer {

    public static void start(String hostname, int port) {
        start0(hostname, port);
    }

    private static void start0(String hostname, int port) {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {

            // 创建服务端启动对象，配置参数
            io.netty.bootstrap.ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap
                    // 设置两个两个线程组
                    .group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new StringDecoder());
                            ch.pipeline().addLast(new StringEncoder());
                            ch.pipeline().addLast(new NettyRpcServerHandler());
                        }
                    })
            ;
            // 绑定端口，并且同步处理
            ChannelFuture channelFuture = serverBootstrap.bind(hostname, port).sync();

            // 对关闭通道进行监听
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {

        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();

        }
    }
}
